<template>
  <div class="form-container">
    <!-- 步骤条 -->
    <el-steps :active="step - 1" finish-status="success" style="margin-bottom: 30px;">
      <el-step title="填写节点信息" />
      <el-step title="安装节点" />
      <el-step title="完成" />
    </el-steps>

    <el-form :model="form" label-width="120px" ref="form" class="form">
      <!-- 步骤1 -->
      <div v-if="step === 1">
        <el-form :model="oneStepForm" label-width="120px" ref="oneStepForm" :rules="oneStepRules">
          <el-form-item label="节点名称" prop="nodeName">
            <el-input v-model="oneStepForm.nodeName" />
          </el-form-item>

          <el-form-item label="IP地址" class="install-option" required>
            <el-button type="text" @click="openAddIpDialog">[添加IP地址]</el-button>
            <span class="help-text">当用于访问节点和域名解析等。</span>
          </el-form-item>

          <el-form-item label="DNS线路" class="dns-option">
            <el-input v-model="form.dnsLine">
              <template slot="append">.{{ mainDomain }}</template>
            </el-input>
            <span class="help-text">当前节点对应的DNS线路,可用线路是根据集群设置的域名获取的,注意DNS服务商可能对这些线路有其他限制。</span>
          </el-form-item>

          <div class="more-options">
            <el-button type="text" @click="toggleSshRemark">
              <span :class="{ 'bold-font': !showSshRemark }">
                {{ showSshRemark ? '收起选项 ▲' : '更多选项 ▼' }}
              </span>
            </el-button>
          </div>

          <el-form-item label="SSH主机地址" prop="sshHost" required v-if="showSshRemark">
            <el-input v-model="oneStepForm.sshHost" />
            <span class="help-text">比如192.168.1.100,用于远程安装节点应用程序。</span>
          </el-form-item>

          <el-form-item label="SSH主机端口" prop="sshPort" required v-if="showSshRemark">
            <el-input v-model="oneStepForm.sshPort"/>
            <span class="help-text">常见的比如22。</span>
          </el-form-item>

          <el-form-item label="SSH登录认证" v-if="showSshRemark">
            <el-button type="text" @click="openSelectAuthDialog">[选择已有认证]</el-button>
            <el-button type="text" @click="openAddAuthDialog">[添加新认证]</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2 -->
      <div v-if="step === 2">
        <el-form-item label="SSH主机地址" required>
          <el-input v-model="twoStepForm.sshHost" placeholder="请输入SSH主机地址" />
        </el-form-item>

        <el-form-item label="SSH主机端口" required>
          <el-input v-model="twoStepForm.sshPort" placeholder="请输入SSH主机端口" />
        </el-form-item>

        <el-form-item label="SSH登录认证" required>
          <el-button type="text" @click="openAddAuthDialog">添加新认证</el-button>
        </el-form-item>

        <el-form-item label="初始化脚本代码">
          <el-select v-model="form.initScript" placeholder="请选择初始化脚本">
            <el-option v-for="item in sshHosts" :key="item" :label="item" :value="item" />
          </el-select>
          <el-button type="text" @click="addScript">添加新脚本代码</el-button>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="form.skipInstall">跳过安装</el-checkbox>
        </el-form-item>
      </div>

      <!-- 步骤3 -->
      <div v-if="step === 3">
        <el-message type="success" show-icon>节点安装完成！</el-message>
      </div>

      <div class="step-actions">
        <!-- 移除“上一步”按钮 -->
        <el-button v-if="step < 3" type="primary" @click="handleNextStep">下一步</el-button>
        <el-button v-if="step === 3" type="primary" @click="handleFinish">完成</el-button>
      </div>

      <!-- 添加IP地址对话框 -->
      <el-dialog title="添加IP地址" :visible.sync="addIpAddressDialogVisible" width="50%">
        <el-form ref="ipForm" :model="ipForm" :rules="ipFormRules" label-width="150px" >
          <el-form-item label="IP地址" prop="ipAddress">
            <el-input v-model="ipForm.ipAddress" />
            <span class="help-text">支持单个IP、CIDR格式的一组IP（位数不能小于24）、IP范围（类似于x.x.x.x,最多只取256个）等。</span>
          </el-form-item>

          <el-form-item label="允许公开访问" class="install-option">
            <el-checkbox v-model="ipForm.publicAccess"></el-checkbox>
            <span class="help-text">是否为可以公开访问的IP，如果选中表示当前IP可以被公开访问，并可被加入到DNS解析记录中。</span>
          </el-form-item>

          <div class="more-options">
            <el-button type="text" @click="toggleRemark">
              <span :class="{ 'bold-font': !showRemark }">
                {{ showRemark ? '收起选项 ▲' : '更多选项 ▼' }}
              </span>
            </el-button>
          </div>

          <el-form-item label="备注" v-if="showRemark">
            <el-input v-model="ipForm.note" placeholder="请输入备注信息" />
          </el-form-item>

          <el-form-item label="在线状态" v-if="showRemark">
            <el-select v-model="ipForm.status">
              <el-option
                v-for="dict in dict.type.edge_nodes_ip_status"
                :key="dict.value"
                :label="dict.label"
                :value="Number(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addIpAddressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addIpConfirm">保存</el-button>
        </span>
      </el-dialog>

      <!-- 选择已有认证对话框 -->
      <el-dialog title="选择已有认证" :visible.sync="selectAuthDialogVisible" width="50%">
        <el-input v-model="searchQuery" placeholder="输入认证名称或SSH用户名进行搜索" @input="searchAuth" style="width: 200px"></el-input>
        <el-table :data="filteredAuthList" stripe @row-click="handleRowClick">
          <el-table-column label="" width="40" align="left">
            <template slot-scope="scope" style="width: auto">
              <el-radio
                v-model="selectedAuth"
                :label="scope.row"
                class="radio"
                :disabled="selectedAuth && selectedAuth !== scope.row"
              />
            </template>
          </el-table-column>
          <el-table-column prop="sshName" label="认证名称" width="auto"></el-table-column>
          <el-table-column prop="sshUser" label="SSH用户名" width="auto"></el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="selectAuthDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="selectAuthConfirm">确定</el-button>
        </span>
      </el-dialog>

      <!-- 添加新认证对话框 -->
      <el-dialog title="添加新认证" :visible.sync="addAuthDialogVisible" width="50%">
        <el-form ref="authForm" :model="authForm" :rules="authRules" label-width="150px" @submit.native.prevent="submitForm">
          <el-form-item label="名称" prop="sshName">
            <el-input v-model="authForm.sshName"></el-input>
            <span class="help-text">为当前认证信息起一个容易识别的名称</span>
          </el-form-item>
          <!-- 认证方式 -->
          <el-form-item label="认证方式">
            <el-select v-model="authForm.sshType">
              <el-option
                v-for="dict in dict.type.edge_nodes_ssh_type"
                :key="dict.value"
                :label="dict.label"
                :value="Number(dict.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="SSH用户名" prop="sshUser">
            <el-input v-model="authForm.sshUser"></el-input>
            <span class="help-text">SSH登录用户名。</span>
          </el-form-item>
          <el-form-item label="SSH密码" prop="sshKey" v-if="authForm.sshType==0">
            <el-input v-model="authForm.sshKey" type="password" show-password></el-input>
            <span class="help-text">SSH登录用户密码，为了安全起见，此项数据保存后将不允许在界面查看完整明文，为避免忘记，请自行记录原始数据。</span>
          </el-form-item>
          <el-form-item label="私钥" prop="sshKey" v-if="authForm.sshType==1">
            <el-input v-model="authForm.sshKey" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="备注" class="remark-form-item" prop="note">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="点击展开备注" name="1">
                <el-input
                  v-model="form.note"
                  type="textarea"
                  :rows="4"
                ></el-input>
              </el-collapse-item>
            </el-collapse>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addAuthDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addAuthConfirm">保存</el-button>
        </span>
      </el-dialog>
    </el-form>
  </div>
</template>


<script>

import {addSsh, listSsh} from "@/api/nodes/ssh";
import {addIp} from "@/api/nodes/ip";
import {addNodes} from "@/api/nodes/nodeInfo";
import {getDnsByClusterId} from "@/api/nodes/clusters";

export default {
  dicts: ['edge_nodes_ip_status','edge_nodes_ssh_type'],
  data() {
    return {
      step: 1, // 当前步骤
      form: {
        // nodeName: '',
        // // group: '',
        // // region: '',
        // cluster: '',
        // sshHost: '',
        // sshPort: '',
        // sshAuth: '',
        // initScript: '',
        // skipInstall: false,
        // installStatus: null,
        // status: null,
      },
      ipForm:{
        // ipAddress: '',
        // skipInstall: false,
        // note: '',
        // publicAccess: false,
        // status: null,
      },
      authForm: {},
      oneStepForm:{},
      twoStepForm:{},
      // nodeId:null,
      showRemark: false,
      addIpAddressDialogVisible: false,
      publicAccess: false,
      showSshRemark: false,
      oneStepRules: {
        nodeName: [{ required: true, message: '节点名称不能为空', trigger: 'blur' }],
        ipAddress: [{ required: true, message: '请选择IP地址', trigger: 'blur' }],
        sshHost: [{ required: true, message: 'SSH主机地址不能为空', trigger: 'blur' }],
        sshPort: [{ required: true, message: 'SSH主机端口不能为空', trigger: 'blur' }],
      },
      ipFormRules: {
        ipAddress: [{ required: true, message: 'IP地址不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择在线状态', trigger: 'change' }],
      },
      authRules:{
        sshName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
      },
      selectAuthDialogVisible: false,
      addAuthDialogVisible: false,
      searchQuery: '',
      filteredAuthList: [],
      authList: [],
      activeNames: [], // 控制折叠面板的展开/收起
      selectedAuth: null, // 用于存储选中的认证信息
      mainDomain:null, // 可用线路主域名
      dnsLine:null, // 节点线路
    };

  },
  created() {
    this.getDnsByClusterId()
  },
  methods: {
    // 查找节点所属集群可用DNS线路
    getDnsByClusterId(){
      getDnsByClusterId(this.$route.params.clusterId).then(response => {
        // 找到第一个 . 的位置
        const dotIndex = response.msg.indexOf('.');
        this.mainDomain = response.msg.substring(dotIndex + 1);
      })
    },
    // 重置表单数据
    reset() {
      this.form = {
        nodeName: '',
        // group: '',
        // region: '',
        cluster: '',
        sshHost: '',
        sshPort: '',
        sshAuth: '',
        initScript: '',
        skipInstall: false,
        installStatus: null,
        status: null,
      };
      this.$refs.form.resetFields();
    },

    // 重置表单数据
    ipFormReset() {
      this.ipForm = {
        ipAddress: '',
        skipInstall: false,
        note: '',
        publicAccess: false,
        status: null,
      };
      this.$refs.ipForm.resetFields();
    },

    // 添加新认证表单重置
    authFormReset() {
      this.authForm = {
        sshName: '',
        sshType: 0,
        sshUser: 'root',
        sshKey: '',
        note: ''
      };
      this.$refs.authForm.resetFields();
    },

    toggleRemark() {
      this.showRemark = !this.showRemark;
    },

    toggleSshRemark() {
      this.showSshRemark = !this.showSshRemark;
    },

    // 打开添加IP对话框
    openAddIpDialog() {
      this.addIpAddressDialogVisible = true;
      this.showRemark = false;
    },

    handleNextStep() {
      if (this.step === 1) {
        // 提交第一步表单
        this.submitOneStepForm();
      } else if (this.step === 2) {
        // 提交第二步数据后跳转到步骤3
        this.step = 3;
      }
    },

    handleFinish() {
      this.$message.success('节点安装完成！');
    },

    // 确认保存IP
    addIpConfirm() {
      this.$refs.ipForm.validate((valid) => {
        if (valid) {
          this.oneStepForm.sshHost = this.ipForm.ipAddress;
          this.twoStepForm.sshHost = this.ipForm.ipAddress;
          this.addIpAddressDialogVisible = false;
        } else {
          this.$message.error('请填写完整的IP地址信息');
        }
      });
    },

    // 打开选择已有认证对话框
    openSelectAuthDialog() {
      this.queryReset();
      this.selectAuthDialogVisible = true;
      this.fetchAuthList(); // 获取认证列表
    },

    // 重置搜索
    queryReset(){
      this.searchQuery= ''
    },

    // 搜索认证
    searchAuth() {
      if (this.searchQuery === '') {
        this.filteredAuthList = this.authList;
      } else {
        this.filteredAuthList = this.authList.filter(auth =>
          auth.sshName.includes(this.searchQuery) || auth.sshUser.includes(this.searchQuery)
        );
      }
    },

    // 选择行
    handleRowClick(row) {
      if (this.selectedAuth === row) {
        this.selectedAuth = null;
        this.form.selectedAuthId = null;
      } else {
        // 选择新的认证
        this.selectedAuth = row;
        this.form.selectedAuthId = row.id;
      }
    },

    // 确认选择的认证
    selectAuthConfirm() {
      if (this.form.selectedAuthId) {
        this.$message.success('认证选择成功！');
        this.selectAuthDialogVisible = false;
      } else {
        this.$message.error('请选择一个认证信息。');
      }
    },

    // 获取认证列表
    fetchAuthList() {
      listSsh().then(response => {
        this.authList = response.rows;
        this.filteredAuthList = this.authList;
      })
    },

    // 打开添加新认证对话框
    openAddAuthDialog(){
      this.addAuthDialogVisible = true;
      this.authFormReset();
    },

    // 添加新认证的确认操作
    addAuthConfirm() {
      // 提交表单
      this.$refs.authForm.validate((valid) => {
        console.log(valid,'valid')
        if (valid) {

          // 表单验证通过，可以提交数据
          addSsh(this.authForm).then(response => {
            this.$message({
              type: 'success',
              message: '认证信息创建成功!'
            });
            this.addAuthDialogVisible = false
          }).catch(error => {
            this.$message({
              type: 'error',
              message: error.response.data.message || '创建认证信息失败，请稍后再试。'
            });
          });
        } else {
          // 表单验证失败
          console.log('表单验证失败');
          return false;
        }
      });
    },

    // 提交第一步的数据
    submitOneStepForm() {
      this.$refs.oneStepForm.validate((valid) => {
        if (valid) {

          this.oneStepForm.clusterId = this.$route.params.clusterId;

          this.oneStepForm.dnsLine = this.form.dnsLine + '.' + this.mainDomain;

          console.log(this.oneStepForm.dnsLine,'this.oneStepForm.dnsLine')
          // 如果选择了认证信息，则添加认证ID到提交的数据中
          if (this.selectedAuth) {
            this.oneStepForm.sshAuthId = this.selectedAuth.id;
          }

          const ipForm = {
            nodeId: null,
            ...this.ipForm,
            publicAccess: this.ipForm.publicAccess ? 0 : 1,
          };

          this.$modal.loading("正在创建节点信息...");

          addNodes(this.oneStepForm)
            .then(response => {
              this.$message({
                type: 'success',
                message: '节点信息创建成功！'
              });
              console.log(response,"response")
              ipForm.nodeId = response.data;
              return addIp(ipForm);
            })
            .then(response => {
              this.$message({
                type: 'success',
                message: '节点IP地址创建成功！'
              });

              // 完成后跳转到第二步
              this.step = 2;  // 保持在步骤2
            })
            .catch(error => {
              console.error('提交 IP 地址失败:', error);

              this.$message({
                type: 'error',
                message: error.response?.data?.message || '创建节点信息失败，请稍后再试。'
              });

              this.$modal.closeLoading();
            })
            .finally(() => {
              this.$modal.closeLoading();
            });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.form-container {
  width: 60%;
  margin: 20px auto;
}

.step-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}

.help-text {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  display: block;
}

.more-options {
  margin-left: 120px;
  bottom: auto;
}

.radio {
  margin-left: 10px;
}
</style>
